package top.superxuqc.loginbili.controller;

import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import top.superxuqc.loginbili.service.DownVideoService;
import top.superxuqc.loginbili.service.LoginService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class Login {
    @Autowired
    LoginService login;

    @Autowired
    private DownVideoService ds;

    @RequestMapping("/RSA")
    @ResponseBody
    public JSONObject getHash(){
        String s = login.solveRSA();
        JSONObject jsonObject = JSONObject.parseObject(s);
        return jsonObject;
    }

    /**
     * web端密码登录
     * @param request
     * @param httpServletResponse
     * @param key
     * @param challenge
     * @param account
     * @param password
     * @param validate
     * @param seccode
     * @return
     */

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse httpServletResponse, String key, String challenge, String account, String password, String validate, String seccode){

        // 登陆 Url
        String loginUrl = "http://passport.bilibili.com/web/login/v2";

        HttpClient httpClient = new HttpClient();


        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);
        System.out.println("进入登录");
        // 设置登陆时要求的信息，用户名和密码
        NameValuePair[] data = { new NameValuePair("captchaType", "6"),
                new NameValuePair("username", account),
                new NameValuePair("password", password),
                new NameValuePair("keep", "true"),
                new NameValuePair("key", key),
                new NameValuePair("challenge", challenge),
                new NameValuePair("validate", validate),
                new NameValuePair("seccode", seccode)
        };
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            postMethod.setRequestHeader("Content_Type","application/json");
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode=httpClient.executeMethod(postMethod);
            System.out.println("登录结果 "+statusCode);

            System.out.println(new String(postMethod.getResponseBody()));
            System.out.println(postMethod.getResponseBodyAsString());
            String result = JSONObject.parseObject(postMethod.getResponseBodyAsString()).getString("message");
            // 获得登陆后的 Cookie
            String cookie = "";
            try {
                cookie = postMethod.getResponseHeader("Set-Cookie").getValue();
            }catch (NullPointerException e){

                ModelAndView mv = new ModelAndView("loginError");
                mv.addObject("result",result);
                return mv;
            }

            Cookie[] cookies = httpClient.getState().getCookies();
            login.set(httpServletResponse,cookies);

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        ModelAndView mv = new ModelAndView("redirect:/");


        return mv;



    }

    /**
     *
     *web端phone登录
     */
    @RequestMapping("/phone_login")
    public ModelAndView plogin(HttpServletRequest request, HttpServletResponse httpServletResponse, String cid, String tel, String smsCode){

        // 登陆 Url
        String loginUrl = "http://passport.bilibili.com/web/login/rapid";

        HttpClient httpClient = new HttpClient();


        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);
        System.out.println("进入登录");
        // 设置登陆时要求的信息，用户名和密码
        NameValuePair[] data = { new NameValuePair("captchaType", "6"),
                new NameValuePair("cid", cid),
                new NameValuePair("tel", tel),
                new NameValuePair("smsCode",smsCode),

        };
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            postMethod.setRequestHeader("Content_Type","application/json");
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode=httpClient.executeMethod(postMethod);
            System.out.println("登录结果 "+statusCode);

            System.out.println(new String(postMethod.getResponseBody()));
            System.out.println(postMethod.getResponseBodyAsString());

            String result = JSONObject.parseObject(postMethod.getResponseBodyAsString()).getString("message");
            // 获得登陆后的 Cookie
            String cookie = "";
            try {
                cookie = postMethod.getResponseHeader("Set-Cookie").getValue();
            }catch (NullPointerException e){

                ModelAndView mv = new ModelAndView("loginError");
                mv.addObject("result",result);
                return mv;
            }


            Cookie[] cookies = httpClient.getState().getCookies();
            login.set(httpServletResponse,cookies,true);

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        ModelAndView mv = new ModelAndView("redirect:/");


        return mv;



    }
    @RequestMapping("/phone_message")
    @ResponseBody
    public String plogin(HttpServletResponse response,String tel,String key,String challenge,String validate,String seccode){
        String cid = "1";
        String type = "21";
        String captchaType = "6";
        // 登陆 Url
        String loginUrl = "http://passport.bilibili.com/web/sms/general/v2/send;";

        HttpClient httpClient = new HttpClient();


        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);
        System.out.println("进入登录");
        // 设置登陆时要求的信息，用户名和密码
        NameValuePair[] data = {
                new NameValuePair("cid", cid),
                new NameValuePair("tel", tel),
                new NameValuePair("key",key),
                new NameValuePair("challenge",challenge),
                new NameValuePair("validate",validate),
                new NameValuePair("seccode",seccode),
                new NameValuePair("type",type),
                new NameValuePair("captchaType",captchaType),

        };
        String result = "";
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            postMethod.setRequestHeader("Content_Type"," application/x-www-form-urlencoded");
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode=httpClient.executeMethod(postMethod);
            System.out.println("登录结果 "+statusCode);

            System.out.println(new String(postMethod.getResponseBody()));
            System.out.println(postMethod.getResponseBodyAsString());

            result = JSONObject.parseObject(postMethod.getResponseBodyAsString()).getString("message");




        }
        catch (Exception e) {

            e.printStackTrace();
            return result;
        }


        response.setStatus(200);

        return result;



    }




    @RequestMapping("/loginApp")
    public ModelAndView loginApp(HttpServletRequest request, HttpServletResponse httpServletResponse, String key, String challenge, String account, String password, String validate, String seccode){

        // 登陆 Url
        String loginUrl = "http://passport.bilibili.com/web/login/v2";

        HttpClient httpClient = new HttpClient();


        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);

        // 设置登陆时要求的信息，用户名和密码
        NameValuePair[] data = { new NameValuePair("captchaType", "6"),
                new NameValuePair("username", account),
                new NameValuePair("password", password),
                new NameValuePair("keep", "true"),
                new NameValuePair("key", key),
                new NameValuePair("challenge", challenge),
                new NameValuePair("validate", validate),
                new NameValuePair("seccode", seccode)
        };
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            postMethod.setRequestHeader("Content_Type","application/json");
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode=httpClient.executeMethod(postMethod);
            String result = JSONObject.parseObject(postMethod.getResponseBodyAsString()).getString("message");
            // 获得登陆后的 Cookie
            String cookie = "";
            try {
                cookie = postMethod.getResponseHeader("Set-Cookie").getValue();
            }catch (NullPointerException e){

                ModelAndView mv = new ModelAndView("loginError");
                mv.addObject("result",result);
                return mv;
            }


            Cookie[] cookies = httpClient.getState().getCookies();
            login.set(httpServletResponse,cookies,true);

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        ModelAndView mv = new ModelAndView("successLogin");


        return mv;



    }

    /**
     *
     *app端phone登录
     */
    @RequestMapping("/appphone_login")
    public ModelAndView Appplogin(HttpServletRequest request, HttpServletResponse httpServletResponse, String cid, String tel, String smsCode){

        // 登陆 Url
        String loginUrl = "http://passport.bilibili.com/web/login/rapid";

        HttpClient httpClient = new HttpClient();


        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);
        System.out.println("进入登录");
        // 设置登陆时要求的信息，用户名和密码
        NameValuePair[] data = { new NameValuePair("captchaType", "6"),
                new NameValuePair("cid", cid),
                new NameValuePair("tel", tel),
                new NameValuePair("smsCode",smsCode),

        };
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            postMethod.setRequestHeader("Content_Type","application/json");
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode=httpClient.executeMethod(postMethod);
            System.out.println("登录结果 "+statusCode);

            System.out.println(new String(postMethod.getResponseBody()));
            System.out.println(postMethod.getResponseBodyAsString());
            String result = JSONObject.parseObject(postMethod.getResponseBodyAsString()).getString("message");
            // 获得登陆后的 Cookie
            String cookie = "";
            try {
                cookie = postMethod.getResponseHeader("Set-Cookie").getValue();
            }catch (NullPointerException e){

                ModelAndView mv = new ModelAndView("loginError");
                mv.addObject("result",result);
                return mv;
            }

            Cookie[] cookies = httpClient.getState().getCookies();
            login.set(httpServletResponse,cookies,true);

        }
        catch (Exception e) {
            e.printStackTrace();
        }

        ModelAndView mv = new ModelAndView("redirect:/");


        return mv;



    }
    @RequestMapping("/appphone_message")
    @ResponseBody
    public String Apppplogin(HttpServletResponse response,String tel,String key,String challenge,String validate,String seccode){
        String cid = "1";
        String type = "21";
        String captchaType = "6";
        // 登陆 Url
        String loginUrl = "http://passport.bilibili.com/web/sms/general/v2/send;";

        HttpClient httpClient = new HttpClient();


        // 模拟登陆，按实际服务器端要求选用 Post 或 Get 请求方式
        PostMethod postMethod = new PostMethod(loginUrl);
        System.out.println("进入登录");
        // 设置登陆时要求的信息，用户名和密码
        NameValuePair[] data = {
                new NameValuePair("cid", cid),
                new NameValuePair("tel", tel),
                new NameValuePair("key",key),
                new NameValuePair("challenge",challenge),
                new NameValuePair("validate",validate),
                new NameValuePair("seccode",seccode),
                new NameValuePair("type",type),
                new NameValuePair("captchaType",captchaType),

        };
        String result = "";
        postMethod.setRequestBody(data);
        try {
            // 设置 HttpClient 接收 Cookie,用与浏览器一样的策略
            postMethod.setRequestHeader("Content_Type"," application/x-www-form-urlencoded");
            httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
            int statusCode=httpClient.executeMethod(postMethod);
            System.out.println("登录结果 "+statusCode);

            System.out.println(new String(postMethod.getResponseBody()));
            System.out.println(postMethod.getResponseBodyAsString());


            result = JSONObject.parseObject(postMethod.getResponseBodyAsString()).getString("message");


        }
        catch (Exception e) {
            response.setStatus(200);


            e.printStackTrace();
            return "error";
        }


        response.setStatus(200);

        return result;



    }


}
